const Response = require('@/utils/response');
const DictionaryService = require('@/service/dictionary');

class DictionaryController {
  async getDictByCode(ctx) { 
    const {code} = ctx.query
    const res = await DictionaryService.getDictByCode(code)
    return Response.success(ctx, res, '获取成功')
  }

  // 保存字典项
  async saveDic(ctx) {
    const params = ctx.request.body;
    try {
      if(!params.value) {
        return Response.error(ctx, '字典项value不能为空', 400);
      }
      if(!params.type_id && !params.type_code) {
        return Response.error(ctx, '字典项分类不能为空', 400);
      }
      if(!params.label) {
        return Response.error(ctx, '字典项label不能为空', 400);
      }
      const res = await DictionaryService.saveItem(params);
      return Response.success(ctx, res, '保存成功');
    } catch (error) {
      return Response.error(ctx, error.message || '保存失败', 500);
    }
  }

  // 删除字典项
  async deleteDic(ctx) {
    const { id } = ctx.request.body;
    try {
      const res = await DictionaryService.deleteItem(id);
      return Response.success(ctx, res, '删除成功');
    } catch (error) {
      return Response.error(ctx, error.message || '删除失败', 500);
    }
  }

  // 字典分类列表
  async getDictCategories(ctx) { 
    try {
      const params = ctx.query;
      const result = await DictionaryService.getCategories(params);
      return Response.success(ctx, result, '获取成功');
    } catch (error) {
      return Response.error(ctx, error.message || '获取失败', 500, error);
    }
  }
  async getDicListAll(ctx) {
    try {
      const result = await DictionaryService.getAllList();
      return Response.success(ctx, result, '获取成功');
    } catch (error) {
      return Response.error(ctx, error.message || '获取失败', 500, error);
    }
  }
  // 保存字典分类
  async saveDictCategory(ctx) { 
    // try {
      const params = ctx.request.body;
      const result = await DictionaryService.saveCategory(params);
      console.log('result', result);
      return Response.success(ctx, result, '保存成功');
    // } catch (error) {
    //   return Response.error(ctx, error.message || '保存失败', 500);
    // }
  }
  // 删除字典分类
  async deleteDictCategory(ctx) { 
    try {
      const { id } = ctx.request.body;
      const result = await DictionaryService.deleteCategory(id);
      return Response.success(ctx, result, '删除成功');
    } catch (error) {
      return Response.error(ctx, error.message || '删除失败', 500);
    }
  }
}

module.exports = new DictionaryController();